import styles from './index.module.scss'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { NavBar, InfiniteScroll } from 'antd-mobile'
import { useAppDispatch, useAppSelector, getSearchResultsAsync } from '@/store/index'
import { useState } from 'react'
import ArticleItem from '@/pages/Home/components/ArticleItem'

const Result = () => {
  const navigate = useNavigate()
  const [params] = useSearchParams()
  const dispatch = useAppDispatch()
  const key = params.get('key') as string
  // 获取搜索结果
  const [page, setPage] = useState(1)

  const {
    result: { results, total_count }
  } = useAppSelector((state) => state.searchSlice)
  // const [hasMore, setHasMore] = useState(true)
  const [loading, setLoading] = useState(false)
  // 1、因为依赖项results变化时，组件刷新，可以直接绑定变量
  const hasMore = total_count >= results.length && page <= 5
  async function loadMore() {
    if (loading) return
    setLoading(true)
    await dispatch(getSearchResultsAsync({ q: key, page }))
    setPage((page) => page + 1)
    setLoading(false)
    // 2、如组件不刷新可，通过state绑定变量刷新组件
    // if (page > 5 || total_count <= results.length) {
    //   setHasMore(false)
    // }
  }
  return (
    <div className={styles.root}>
      <NavBar onBack={() => navigate(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item) => (
          <ArticleItem key={item.art_id} article={item}></ArticleItem>
        ))}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}></InfiniteScroll>
      </div>
    </div>
  )
}

export default Result
